<!DOCTYPE html>
<html>
<head>
    

    

    



    <meta charset="utf-8">
    
    
    
    <title>分布式ID生成器-Sequence | 尼古拉斯-鱼丸博客 | 喝酒、吃肉、不赌</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="分布式ID生成器,Snowflake">
    <meta name="description" content="分布式系统高效ID生成工具什么是Sequence?高效GUID产生算法(sequence),基于Snowflake实现64位自增ID算法。 链接: sequence 什么是Snowflake？Twitter的分布式自增ID算法snowflake  1.概述  分布式系统中，有一些需要使用全局唯一ID的场景，这种时候为了防止ID冲突可以使用36位的UUID，但是UUID有一些缺点，首先他相对比较长，">
<meta name="keywords" content="分布式ID生成器,Snowflake">
<meta property="og:type" content="article">
<meta property="og:title" content="分布式ID生成器-Sequence">
<meta property="og:url" content="http://fish_08.oschina.io/2017/06/21/sequence/index.html">
<meta property="og:site_name" content="尼古拉斯-鱼丸博客">
<meta property="og:description" content="分布式系统高效ID生成工具什么是Sequence?高效GUID产生算法(sequence),基于Snowflake实现64位自增ID算法。 链接: sequence 什么是Snowflake？Twitter的分布式自增ID算法snowflake  1.概述  分布式系统中，有一些需要使用全局唯一ID的场景，这种时候为了防止ID冲突可以使用36位的UUID，但是UUID有一些缺点，首先他相对比较长，">
<meta property="og:updated_time" content="2017-06-28T08:16:51.575Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="分布式ID生成器-Sequence">
<meta name="twitter:description" content="分布式系统高效ID生成工具什么是Sequence?高效GUID产生算法(sequence),基于Snowflake实现64位自增ID算法。 链接: sequence 什么是Snowflake？Twitter的分布式自增ID算法snowflake  1.概述  分布式系统中，有一些需要使用全局唯一ID的场景，这种时候为了防止ID冲突可以使用36位的UUID，但是UUID有一些缺点，首先他相对比较长，">
    
        <link rel="alternative" href="/atom.xml" title="尼古拉斯-鱼丸博客" type="application/atom+xml">
    
    <link rel="shortcut icon" href="/favicon.ico">
    <link rel="stylesheet" href="/css/style.css?v=1.6.7">
    <script>window.lazyScripts=[]</script>
</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap">
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">于亮</h5>
          <a href="mailto:136214289@qq.com" title="136214289@qq.com" class="mail">136214289@qq.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                文档
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                标签
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="http://git.oschina.net/fish_08" target="_blank" >
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="http://weibo.com/2837335591/profile?rightmod=1&wvr=6&mod=personinfo" target="_blank" >
                <i class="icon icon-lg icon-weibo"></i>
                Weibo
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/custom"  >
                <i class="icon icon-lg icon-link"></i>
                测试
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">分布式ID生成器-Sequence</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">分布式ID生成器-Sequence</h1>
        <h5 class="subtitle">
            
                <time datetime="2017-06-21T07:56:06.000Z" itemprop="datePublished" class="page-time">
  2017-06-21
</time>


            
        </h5>
    </div>

    

</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#分布式系统高效ID生成工具"><span class="post-toc-number">1.</span> <span class="post-toc-text">分布式系统高效ID生成工具</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#什么是Sequence"><span class="post-toc-number">1.1.</span> <span class="post-toc-text">什么是Sequence?</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#什么是Snowflake？"><span class="post-toc-number">1.2.</span> <span class="post-toc-text">什么是Snowflake？</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#IdWorker获取自增ID"><span class="post-toc-number">1.3.</span> <span class="post-toc-text">IdWorker获取自增ID</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#IdWorker依赖工具类Sequence"><span class="post-toc-number">1.4.</span> <span class="post-toc-text">IdWorker依赖工具类Sequence</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#IdWorker依赖工具类SystemClock"><span class="post-toc-number">1.5.</span> <span class="post-toc-text">IdWorker依赖工具类SystemClock</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#IdWorker-测试"><span class="post-toc-number">1.6.</span> <span class="post-toc-text">IdWorker 测试</span></a></li></ol></li></ol>
        </nav>
    </aside>
    
<article id="post-sequence"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">分布式ID生成器-Sequence</h1>
        <div class="post-meta">
            <time class="post-time" title="2017年06月21日 15:56" datetime="2017-06-21T07:56:06.000Z"  itemprop="datePublished">2017-06-21</time>

            


            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


            

        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <h2 id="分布式系统高效ID生成工具"><a href="#分布式系统高效ID生成工具" class="headerlink" title="分布式系统高效ID生成工具"></a>分布式系统高效ID生成工具</h2><h3 id="什么是Sequence"><a href="#什么是Sequence" class="headerlink" title="什么是Sequence?"></a>什么是Sequence?</h3><pre><code>高效GUID产生算法(sequence),基于Snowflake实现64位自增ID算法。
</code></pre><p>链接: <a href="http://git.oschina.net/yu120/sequence" target="_blank" rel="external">sequence</a></p>
<h3 id="什么是Snowflake？"><a href="#什么是Snowflake？" class="headerlink" title="什么是Snowflake？"></a>什么是Snowflake？</h3><p>Twitter的分布式自增ID算法snowflake </p>
<p>1.概述<br>  分布式系统中，有一些需要使用全局唯一ID的场景，这种时候为了防止ID冲突可以使用36位的UUID，但是UUID有一些缺点，首先他相对比较长，另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID，并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求，最初Twitter把存储系统从MySQL迁移到Cassandra，因为Cassandra没有顺序ID生成机制，所以开发了这样一套全局唯一ID生成服务。<br>  核心思想是：使用41bit作为毫秒数，10bit作为机器的ID（5个bit是数据中心，5个bit的机器ID），12bit作为毫秒内的流水号（意味着每个节点在每毫秒可以产生 4096 个 ID），最后还有一个符号位，永远是0。</p>
<p>2.结构<br>  snowflake的结构如下(每部分用-分开):<br>  0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000<br>  第一位为未使用标识正负，接下来的41位为毫秒级时间(41位的长度可以使用69年)，然后是5位datacenterId和5位workerId(10位的长度最多支持部署1024个节点） ，最后12位是毫秒内的计数（12位的计数顺序号支持每个节点每毫秒产生4096个ID序号）一共加起来刚好64位，为一个Long型。(转换成字符串长度为18)<br>  snowflake生成的ID整体上按照时间自增排序，并且整个分布式系统内不会产生ID碰撞（由datacenter和workerId作区分），并且效率较高。据说：snowflake每秒能够产生26万个ID。</p>
<h3 id="IdWorker获取自增ID"><a href="#IdWorker获取自增ID" class="headerlink" title="IdWorker获取自增ID"></a>IdWorker获取自增ID</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div></pre></td><td class="code"><pre><div class="line">/**</div><div class="line"> * &lt;p&gt;</div><div class="line"> * 高效GUID产生算法(sequence),基于Snowflake实现64位自增ID算法。 &lt;br&gt;</div><div class="line"> * 优化开源项目 http://git.oschina.net/yu120/sequence</div><div class="line"> * &lt;/p&gt;</div><div class="line"> *</div><div class="line"> * @author hubin</div><div class="line"> * @Date 2016-08-01</div><div class="line"> */</div><div class="line">public class IdWorker &#123;</div><div class="line"></div><div class="line">	/**</div><div class="line">	 * 主机和进程的机器码</div><div class="line">	 */</div><div class="line">	private static Sequence worker = new Sequence();</div><div class="line"></div><div class="line">	public static long <span class="function"><span class="title">getId</span></span>() &#123;</div><div class="line">		<span class="built_in">return</span> worker.nextId();</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	/**</div><div class="line">	 * &lt;p&gt;</div><div class="line">	 * 获取去掉<span class="string">"-"</span> UUID</div><div class="line">	 * &lt;/p&gt;</div><div class="line">	 */</div><div class="line">	public static synchronized String <span class="function"><span class="title">get32UUID</span></span>() &#123;</div><div class="line">		<span class="built_in">return</span> UUID.randomUUID().toString().replace(<span class="string">"-"</span>, <span class="string">""</span>);</div><div class="line">	&#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="IdWorker依赖工具类Sequence"><a href="#IdWorker依赖工具类Sequence" class="headerlink" title="IdWorker依赖工具类Sequence"></a>IdWorker依赖工具类Sequence</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div><div class="line">102</div><div class="line">103</div><div class="line">104</div><div class="line">105</div><div class="line">106</div><div class="line">107</div><div class="line">108</div><div class="line">109</div><div class="line">110</div><div class="line">111</div><div class="line">112</div><div class="line">113</div><div class="line">114</div><div class="line">115</div><div class="line">116</div><div class="line">117</div><div class="line">118</div><div class="line">119</div><div class="line">120</div><div class="line">121</div><div class="line">122</div><div class="line">123</div><div class="line">124</div><div class="line">125</div><div class="line">126</div><div class="line">127</div><div class="line">128</div><div class="line">129</div><div class="line">130</div><div class="line">131</div><div class="line">132</div><div class="line">133</div><div class="line">134</div><div class="line">135</div><div class="line">136</div><div class="line">137</div><div class="line">138</div><div class="line">139</div><div class="line">140</div><div class="line">141</div><div class="line">142</div><div class="line">143</div><div class="line">144</div><div class="line">145</div><div class="line">146</div><div class="line">147</div><div class="line">148</div><div class="line">149</div></pre></td><td class="code"><pre><div class="line"></div><div class="line">public class Sequence &#123;</div><div class="line">	private static final Log logger = LogFactory.getLog(Sequence.class);</div><div class="line"></div><div class="line">	/* 时间起始标记点，作为基准，一般取系统的最近时间（一旦确定不能变动） */</div><div class="line">	private final long twepoch = 1288834974657L;</div><div class="line">	private final long workerIdBits = 5L;/* 机器标识位数 */</div><div class="line">	private final long datacenterIdBits = 5L;</div><div class="line">	private final long maxWorkerId = -1L ^ (-1L &lt;&lt; workerIdBits);</div><div class="line">	private final long maxDatacenterId = -1L ^ (-1L &lt;&lt; datacenterIdBits);</div><div class="line">	private final long sequenceBits = 12L;/* 毫秒内自增位 */</div><div class="line">	private final long workerIdShift = sequenceBits;</div><div class="line">	private final long datacenterIdShift = sequenceBits + workerIdBits;</div><div class="line">	/* 时间戳左移动位 */</div><div class="line">	private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;</div><div class="line">	private final long sequenceMask = -1L ^ (-1L &lt;&lt; sequenceBits);</div><div class="line"></div><div class="line">	private long workerId;</div><div class="line"></div><div class="line">	/* 数据标识id部分 */</div><div class="line">	private long datacenterId;</div><div class="line">	private long sequence = 0L;/* 0，并发控制 */</div><div class="line">	private long lastTimestamp = -1L;/* 上次生产id时间戳 */</div><div class="line"></div><div class="line">	public <span class="function"><span class="title">Sequence</span></span>() &#123;</div><div class="line">		this.datacenterId = getDatacenterId(maxDatacenterId);</div><div class="line">		this.workerId = getMaxWorkerId(datacenterId, maxWorkerId);</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	/**</div><div class="line">	 * @param workerId</div><div class="line">	 *            工作机器ID</div><div class="line">	 * @param datacenterId</div><div class="line">	 *            序列号</div><div class="line">	 */</div><div class="line">	public Sequence(long workerId, long datacenterId) &#123;</div><div class="line">		<span class="keyword">if</span> (workerId &gt; maxWorkerId || workerId &lt; 0) &#123;</div><div class="line">			try &#123;</div><div class="line">				throw new RuntimeException(String.format(<span class="string">"worker Id can't be greater than %d or less than 0"</span>, maxWorkerId));</div><div class="line">			&#125; catch (RuntimeException e) &#123;</div><div class="line">				<span class="keyword">if</span>(logger.isDebugEnabled())&#123;</div><div class="line">					logger.debug(String.format(<span class="string">"worker Id can't be greater than %d or less than 0"</span>, maxWorkerId));</div><div class="line">				&#125;</div><div class="line">			&#125;</div><div class="line">		&#125;</div><div class="line">		<span class="keyword">if</span> (datacenterId &gt; maxDatacenterId || datacenterId &lt; 0) &#123;</div><div class="line">			try &#123;</div><div class="line">				throw new RuntimeException(</div><div class="line">                        String.format(<span class="string">"datacenter Id can't be greater than %d or less than 0"</span>, maxDatacenterId));</div><div class="line">			&#125; catch (RuntimeException e) &#123;</div><div class="line">				<span class="keyword">if</span>(logger.isDebugEnabled())&#123;</div><div class="line">					logger.debug(String.format(<span class="string">"datacenter Id can't be greater than %d or less than 0"</span>, maxDatacenterId));</div><div class="line">				&#125;</div><div class="line">			&#125;</div><div class="line">		&#125;</div><div class="line">		this.workerId = workerId;</div><div class="line">		this.datacenterId = datacenterId;</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	/**</div><div class="line">	 * 获取下一个ID</div><div class="line">	 *</div><div class="line">	 * @<span class="built_in">return</span></div><div class="line">	 */</div><div class="line">	public synchronized long <span class="function"><span class="title">nextId</span></span>() &#123;</div><div class="line">		long timestamp = timeGen();</div><div class="line">		<span class="keyword">if</span> (timestamp &lt; lastTimestamp) &#123;</div><div class="line">			try &#123;</div><div class="line">				throw new RuntimeException(String.format(<span class="string">"Clock moved backwards. Refusing to generate id for %d milliseconds"</span>,</div><div class="line">                        lastTimestamp - timestamp));</div><div class="line">			&#125; catch (RuntimeException e) &#123;</div><div class="line">				<span class="keyword">if</span>(logger.isDebugEnabled())&#123;</div><div class="line">					logger.debug(String.format(<span class="string">"Clock moved backwards. Refusing to generate id for %d milliseconds"</span>,</div><div class="line">							lastTimestamp - timestamp));</div><div class="line">				&#125;</div><div class="line">			&#125;</div><div class="line">		&#125;</div><div class="line">		<span class="keyword">if</span> (lastTimestamp == timestamp) &#123;</div><div class="line">			sequence = (sequence + 1) &amp; sequenceMask;</div><div class="line">			<span class="keyword">if</span> (sequence == 0) &#123;</div><div class="line">				timestamp = tilNextMillis(lastTimestamp);</div><div class="line">			&#125;</div><div class="line">		&#125; <span class="keyword">else</span> &#123;</div><div class="line">			sequence = 0L;</div><div class="line">		&#125;</div><div class="line"></div><div class="line">		lastTimestamp = timestamp;</div><div class="line"></div><div class="line">		<span class="built_in">return</span> ((timestamp - twepoch) &lt;&lt; timestampLeftShift) | (datacenterId &lt;&lt; datacenterIdShift) | (workerId &lt;&lt; workerIdShift)</div><div class="line">				| sequence;</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	protected long tilNextMillis(long lastTimestamp) &#123;</div><div class="line">		long timestamp = timeGen();</div><div class="line">		<span class="keyword">while</span> (timestamp &lt;= lastTimestamp) &#123;</div><div class="line">			timestamp = timeGen();</div><div class="line">		&#125;</div><div class="line">		<span class="built_in">return</span> timestamp;</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	protected long <span class="function"><span class="title">timeGen</span></span>() &#123;</div><div class="line">		<span class="built_in">return</span> SystemClock.now();</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	/**</div><div class="line">	 * &lt;p&gt;</div><div class="line">	 * 获取 maxWorkerId</div><div class="line">	 * &lt;/p&gt;</div><div class="line">	 */</div><div class="line">	protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) &#123;</div><div class="line">		StringBuffer mpid = new StringBuffer();</div><div class="line">		mpid.append(datacenterId);</div><div class="line">		String name = ManagementFactory.getRuntimeMXBean().getName();</div><div class="line">		<span class="keyword">if</span> (StringUtils.isNotEmpty(name)) &#123;</div><div class="line">			/*</div><div class="line">			 * GET jvmPid</div><div class="line">			 */</div><div class="line">			mpid.append(name.split(<span class="string">"@"</span>)[0]);</div><div class="line">		&#125;</div><div class="line">		/*</div><div class="line">		 * MAC + PID 的 hashcode 获取16个低位</div><div class="line">		 */</div><div class="line">		<span class="built_in">return</span> (mpid.toString().hashCode() &amp; 0xffff) % (maxWorkerId + 1);</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	/**</div><div class="line">	 * &lt;p&gt;</div><div class="line">	 * 数据标识id部分</div><div class="line">	 * &lt;/p&gt;</div><div class="line">	 */</div><div class="line">	protected static long getDatacenterId(long maxDatacenterId) &#123;</div><div class="line">		long id = 0L;</div><div class="line">		try &#123;</div><div class="line">			InetAddress ip = InetAddress.getLocalHost();</div><div class="line">			NetworkInterface network = NetworkInterface.getByInetAddress(ip);</div><div class="line">			<span class="keyword">if</span> (network == null) &#123;</div><div class="line">				id = 1L;</div><div class="line">			&#125; <span class="keyword">else</span> &#123;</div><div class="line">				byte[] mac = network.getHardwareAddress();</div><div class="line">				id = ((0x000000FF &amp; (long) mac[mac.length - 1]) | (0x0000FF00 &amp; (((long) mac[mac.length - 2]) &lt;&lt; 8))) &gt;&gt; 6;</div><div class="line">				id = id % (maxDatacenterId + 1);</div><div class="line">			&#125;</div><div class="line">		&#125; catch (Exception e) &#123;</div><div class="line">			logger.warn(<span class="string">" getDatacenterId: "</span> + e.getMessage());</div><div class="line">		&#125;</div><div class="line">		<span class="built_in">return</span> id;</div><div class="line">	&#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="IdWorker依赖工具类SystemClock"><a href="#IdWorker依赖工具类SystemClock" class="headerlink" title="IdWorker依赖工具类SystemClock"></a>IdWorker依赖工具类SystemClock</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div></pre></td><td class="code"><pre><div class="line">/**</div><div class="line"> * &lt;p&gt;</div><div class="line"> * 高并发场景下System.currentTimeMillis()的性能问题的优化</div><div class="line"> * &lt;/p&gt;</div><div class="line"> * &lt;p&gt;</div><div class="line"> * System.currentTimeMillis()的调用比new一个普通对象要耗时的多（具体耗时高出多少我还没测试过，有人说是100倍左右）&lt;br&gt;</div><div class="line"> * System.currentTimeMillis()之所以慢是因为去跟系统打了一次交道&lt;br&gt;</div><div class="line"> * 后台定时更新时钟，JVM退出时，线程自动回收&lt;br&gt;</div><div class="line"> * 10亿：43410,206,210.72815533980582%&lt;br&gt;</div><div class="line"> * 1亿：4699,29,162.0344827586207%&lt;br&gt;</div><div class="line"> * 1000万：480,12,40.0%&lt;br&gt;</div><div class="line"> * 100万：50,10,5.0%&lt;br&gt;</div><div class="line"> * &lt;/p&gt;</div><div class="line"> *</div><div class="line"> * @author hubin</div><div class="line"> * @Date 2016-08-01</div><div class="line"> */</div><div class="line">public class SystemClock &#123;</div><div class="line"></div><div class="line">    private final long period;</div><div class="line">    private final AtomicLong now;</div><div class="line"></div><div class="line">    private SystemClock(long period) &#123;</div><div class="line">        this.period = period;</div><div class="line">        this.now = new AtomicLong(System.currentTimeMillis());</div><div class="line">        scheduleClockUpdating();</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    private static class InstanceHolder &#123;</div><div class="line">        public static final SystemClock INSTANCE = new SystemClock(1);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    private static SystemClock <span class="function"><span class="title">instance</span></span>() &#123;</div><div class="line">        <span class="built_in">return</span> InstanceHolder.INSTANCE;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    private void <span class="function"><span class="title">scheduleClockUpdating</span></span>() &#123;</div><div class="line">        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new <span class="function"><span class="title">ThreadFactory</span></span>() &#123;</div><div class="line">            public Thread newThread(Runnable runnable) &#123;</div><div class="line">                Thread thread = new Thread(runnable, <span class="string">"System Clock"</span>);</div><div class="line">                thread.setDaemon(<span class="literal">true</span>);</div><div class="line">                <span class="built_in">return</span> thread;</div><div class="line">            &#125;</div><div class="line">        &#125;);</div><div class="line">        scheduler.scheduleAtFixedRate(new <span class="function"><span class="title">Runnable</span></span>() &#123;</div><div class="line">            public void <span class="function"><span class="title">run</span></span>() &#123;</div><div class="line">                now.set(System.currentTimeMillis());</div><div class="line">            &#125;</div><div class="line">        &#125;, period, period, TimeUnit.MILLISECONDS);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    private long <span class="function"><span class="title">currentTimeMillis</span></span>() &#123;</div><div class="line">        <span class="built_in">return</span> now.get();</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    public static long <span class="function"><span class="title">now</span></span>() &#123;</div><div class="line">        <span class="built_in">return</span> instance().currentTimeMillis();</div><div class="line">    &#125;</div><div class="line">    </div><div class="line">	public static String <span class="function"><span class="title">nowDate</span></span>() &#123;</div><div class="line">		<span class="built_in">return</span> new Timestamp(instance().currentTimeMillis()).toString();</div><div class="line">	&#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>链接:<a href="http://mp.baomidou.com/#/generate-code" target="_blank" rel="external">Mybatis-plus</a></p>
<h3 id="IdWorker-测试"><a href="#IdWorker-测试" class="headerlink" title="IdWorker 测试"></a>IdWorker 测试</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">Long id=IdWorker.getId();</div></pre></td></tr></table></figure>
        </div>

        <blockquote class="post-copyright">
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2017-06-28T08:16:51.575Z" itemprop="dateUpdated">2017年6月28日 16:16</time>
</span><br>


        如要转载请注明出处：<a href="/2017/06/21/sequence/" target="_blank" rel="external">http://fish_08.oschina.io/2017/06/21/sequence/</a>
    </div>
    <footer>
        <a href="http://fish_08.oschina.io">
            <img src="/img/avatar.jpg" alt="于亮">
            于亮
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Snowflake/">Snowflake</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/分布式ID生成器/">分布式ID生成器</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://fish_08.oschina.io/2017/06/21/sequence/&title=《分布式ID生成器-Sequence》 — 尼古拉斯-鱼丸博客&pic=http://fish_08.oschina.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://fish_08.oschina.io/2017/06/21/sequence/&title=《分布式ID生成器-Sequence》 — 尼古拉斯-鱼丸博客&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://fish_08.oschina.io/2017/06/21/sequence/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《分布式ID生成器-Sequence》 — 尼古拉斯-鱼丸博客&url=http://fish_08.oschina.io/2017/06/21/sequence/&via=http://fish_08.oschina.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://fish_08.oschina.io/2017/06/21/sequence/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2017/06/23/QRcode/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">zxing后台二维码生成和解析类库</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2017/06/15/hexo-use/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">Hexo+码云个人微博搭建</h4>
      </a>
    </div>
  
</nav>



    







</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        谢谢包子~
        <i class="icon icon-quote-right"></i>
    </h3>
    <ul class="reward-items">
        
        <li>
            <img src="/img/wechat.png" title="微信打赏二维码" alt="微信打赏二维码">
            <p>微信</p>
        </li>
        

        
        <li>
            <img src="/img/alipay.png" title="支付宝打赏二维码" alt="支付宝打赏二维码">
            <p>支付宝</p>
        </li>
        
    </ul>
</div>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            <span><a href="/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            <span>博客内容遵循 <a href="http://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">知识共享 署名 - 非商业性 - 相同方式共享 4.0协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p>
            <span>Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="http://fish_08.oschina.io/" target="_blank">yuliang</a></span>
            <span>尼古拉斯-鱼丸博客 &copy; 2015 - 2018</span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://fish_08.oschina.io/2017/06/21/sequence/&title=《分布式ID生成器-Sequence》 — 尼古拉斯-鱼丸博客&pic=http://fish_08.oschina.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://fish_08.oschina.io/2017/06/21/sequence/&title=《分布式ID生成器-Sequence》 — 尼古拉斯-鱼丸博客&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://fish_08.oschina.io/2017/06/21/sequence/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《分布式ID生成器-Sequence》 — 尼古拉斯-鱼丸博客&url=http://fish_08.oschina.io/2017/06/21/sequence/&via=http://fish_08.oschina.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://fish_08.oschina.io/2017/06/21/sequence/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: true };



</script>

<script src="/js/main.min.js?v=1.6.7"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="/js/search.min.js?v=1.6.7" async></script>






<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>


</body>
</html>
